package com.yushixin.account.service.impl;

import com.yushixin.account.model.Account;
import com.yushixin.account.repository.IAccountRepository;
import com.yushixin.account.service.IAccountService;
import com.yushixin.account.service.MQProducerService;
import com.yushixin.common.annotation.Read;
import com.yushixin.common.annotation.Write;
import com.yushixin.common.constant.Constant;
import com.yushixin.common.util.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 账户服务层实现类
 */
@Service
@Read
@Slf4j
public class AccountServiceImpl implements IAccountService {
    
    @Autowired
    private IAccountRepository accountRepository;
    
    @Autowired
    private MQProducerService producerService;
    
    @Override
    public List<Account> findAll() {
        return accountRepository.findAll(Sort.by("id"));
    }
    
    @Override
    public Account findByUsername(String username) {
        return accountRepository.findAccountByUsername(username);
    }
    
    @Override
    @Write
    public void addAccount(Account account) {
        try {
        
        } catch (Exception e) {
        
        }
        Account hasExists = accountRepository.findAccountByUsername(account.getUsername());
        if (Objects.nonNull(hasExists)) {
            throw new RuntimeException("用户名已存在");
        }
        account.setId(SnowflakeIdWorker.generateId());
        account.setStatus(0);
        // 新增账户
        accountRepository.save(account);
        // 发送新增消息
        producerService.sendTagMassage(Constant.MQTagAdd, account);
    }
    
    @Override
    @Write
    public void updateAccount(Account account) {
        Optional<Account> optional = accountRepository.findById(account.getId());
        if (optional.isPresent()) {
            Account value = optional.get();
            // 修改账户
            BeanUtils.copyProperties(account, value, "id");
            accountRepository.save(value);
            // 发送修改消息
            producerService.sendTagMassage(Constant.MQTagUpdate, value);
        } else {
            throw new RuntimeException("记录不存在");
        }
    }
    
    @Override
    @Write
    public void deleteAccount(Long id) {
        Optional<Account> optional = accountRepository.findById(id);
        if (optional.isPresent()) {
            Account value = optional.get();
            // 删除账户
            accountRepository.delete(value);
            // 发送删除消息
            Account message = new Account();
            message.setId(id);
            producerService.sendTagMassage(Constant.MQTagDelete, message);
        } else {
            throw new RuntimeException("记录不存在");
        }
    }
}